#include "board.h"
#include "ti_msp_dl_config.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "openmv.h"
#define RECEIVE_LENGTH 256
volatile char recv_buf[RECEIVE_LENGTH];
volatile int recv_len = 0;
volatile int cont_ = 0;
volatile bool rx_flag = 0;
boxdata box;
void openmv_data(void){
  if (rx_flag) {
      float buf_numbers[4];
      int count = 0;
      // 去掉首尾的 '[' 和 ']'
      char *start = recv_buf + 1;
      char *end = strchr(start, ']');
      if (end != NULL) {
         *end = '\0';
        }
      // 使用 strtok 分割字符串
      char *token = strtok(start, ",");
      while (token != NULL && count < 4) {
        buf_numbers[count++] = atof(token); // 将字符串转换为 float
        token = strtok(NULL, ",");
      }
      //打印验证
    //   for (int i = 0; i < count; i++) {
    //     lc_printf("%.2f\n", buf_numbers[i]);
    //   }
      box.dx = buf_numbers[0];
      box.dy = buf_numbers[1];

      //lc_printf("box: dx=%.2f dy=%.2f\n", box.dx, box.dy);
      cont_ = 0;
      rx_flag = 0;
      recv_len = 0;
      memset(recv_buf, 0, RECEIVE_LENGTH);

    }
}
void uart0_send_char(char ch) {
  // 当串口0忙的时候等待，不忙的时候再发送传进来的字符
  while (DL_UART_isBusy(UART_0_INST) == true)
    ;
  // 发送单个字符
  DL_UART_Main_transmitData(UART_0_INST, ch);
}
void UART_0_INST_IRQHandler(void) {

  // 如果产生了串口中断
    switch (DL_UART_getPendingInterrupt(UART_0_INST)) {
    case DL_UART_IIDX_RX: // 如果是接收中断
    char rx_date = DL_UART_Main_receiveData(UART_0_INST);
    if (recv_buf[0] != '[') {
      rx_flag = 0;
      recv_len = 0;
      cont_ = 0;
      memset(recv_buf, 0, RECEIVE_LENGTH);
    }
    if (recv_len < RECEIVE_LENGTH - 1) {
      recv_buf[recv_len] = rx_date;
      if (recv_buf[0] == '[' && recv_buf[recv_len] == ']') {
        rx_flag = 1;
        return;
      }
      recv_len++;
    } else {
      rx_flag = 0;
      recv_len = 0;
      cont_ = 0;
      memset(recv_buf, 0, RECEIVE_LENGTH);
    }
    break;
  default: // 其他的串口中断
    break;
  }
}